from django.shortcuts import render
from . import models
from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
import jsonpickle
from django.views.decorators.clickjacking import xframe_options_exempt
from HOL4inWeb import password
import os
from search import function
from search.views import translate

# Create your views here.
@xframe_options_exempt
def requests_history(request):
    user = request.session.get('login', None)
    if user:
        user = models.AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
        if user.admin == 1:
            result = models.RequestHistory.objects.filter().exclude(ip="127.0.0.1").order_by('-time')
        else:
            errormsg = "您没有管理权限"
    else:
        return HttpResponseRedirect('/')

    return render(request, 'webadmin/request_history.html', locals())

def index(request):
    user = request.session.get('login', None)
    if user:
        user = models.AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
        if user.admin == 1:
            pass
        else:
            errormsg = "您没有管理权限"
    else:
        return HttpResponseRedirect('/')

    return render(request, 'webadmin/index.html', locals())

def updateDB(request):
    user = request.session.get('login', None)
    if user:
        user = AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
        if user.admin == 1:
            import os
            fileList = os.listdir()

class docfile(object):

    def __init__(self, filename, mtime, ntime, name, stru):
        self.filename = filename
        self.mtime = mtime
        self.ntime = ntime
        self.name = name
        self.stru = stru


@xframe_options_exempt
def docfiles(request):
    user = request.session.get('login', None)
    if user:
        user = models.AccountUser.objects.get(uid=jsonpickle.loads(user).uid)
        if user.admin == 1:
            fileList = []
            tr = request.GET.get('tr', None)
            if tr:
                name = request.GET.get('name')
                stru = request.GET.get('stru')
                translate(None,True,name,stru)
            for count,each in enumerate(os.listdir(password.DOCPATH)):
                if each[-4:] == ".doc":
                    try:
                        stru = each[:-4].split('.')[0]
                        name = each[:-4].split('.')[1]
                        try:
                            if stru == 'Thm':
                                stru = 'FinalThm'
                            ntime = models.Tactic.objects.get(name=name,structure__name=stru).updatetime
                            if not ntime: 
                                ntime = function.time_to_datetime(60000)
                        except:
                            ntime = function.time_to_datetime(0)
                        aDoc = docfile(filename=each, mtime=function.time_to_datetime(os.stat(os.path.join(password.DOCPATH, each)).st_mtime), ntime=ntime, name=name, stru=stru)
                        fileList.append(aDoc)
                    except Exception as e:
                        print("webadmin.views.docfiles error: ",each, e)
                        fileList.append(docfile(filename=each, mtime=function.time_to_datetime(os.stat(os.path.join(password.DOCPATH, each)).st_mtime), ntime=function.time_to_datetime(660), name=None, stru=each[:-4]))
                    sort = request.GET.get('sort', 'nt')
                    if sort == 'ntr':
                        fileList = sorted(fileList, key=lambda x: x.ntime, reverse=True)
                    if sort == 'nt':
                        fileList = sorted(fileList, key=lambda x: x.ntime)
                    if sort == 'mtr':
                        fileList = sorted(fileList, key=lambda x: x.mtime, reverse=True)
                    if sort == 'mt':
                        fileList = sorted(fileList, key=lambda x: x.mtime)
            return render(request, 'webadmin/docfiles.html', locals())

